#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Morphological analyser for Russian and English languages
using converted AOT (http://www.aot.ru/download.php) dictionaries.

Conversion script is included.

@author:  Mikhail Korobov <kmike84@gmail.com>
@license: MIT

Copyright (c) Mikhail Korobov <kmike84@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""

import subprocess
import os
import re

_lemmatizer = None;

def stem(word):
    global _lemmatizer;
    if _lemmatizer is None:
        _lemmatizer = Lemmatizer();
    return _lemmatizer.normalize(word)

re_latin=re.compile("[a-zA-Z]")
re_normalform=re.compile("{.+?")

class Lemmatizer():

    def __init__(self):
        p=os.environ
        p["RML"]="./Morphology"
        self.rus=subprocess.Popen("./Morphology/Bin/TestLem Russian",shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,env=p)
        while (self.rus.stdout.readline().strip()!="ready"):
            pass
        self.eng=subprocess.Popen("./Morphology/Bin/TestLem English",shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,env=p)
        while (self.eng.stdout.readline().strip()!="ready"):
            pass

    def normalize(self,word):
        out=""
        word=word.encode('cp1251','ignore')
        if (word!=""):
            if (re_latin.match(word)):
                self.eng.stdin.write(word+"\n")
                out=self.eng.stdout.readline().strip()
                while (self.eng.stdout.readline()!="ready\n"):
                    pass
            else:
                self.rus.stdin.write(word+"\n")
                out=self.rus.stdout.readline().strip();
                if out.startswith('ready'):
                  return unicode(word, "cp1251", "ignore").upper();
                while (self.rus.stdout.readline()!="ready\n"):
                    pass
        return unicode(out,"cp1251","ignore");

    def __del__(self):
        self.rus.stdin.write("\n")
        self.eng.stdin.write("\n")
